/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * @author Abahe
 */
public class DemoRMS extends MIDlet implements CommandListener {

    private Display display;
    private Form form;
    private RecordStore rs;
    private RecordEnumeration re;
    private ChoiceGroup choicegorup;
    private Alert alert;
    private List list;
    //utk proses entri data
    private Form entri;
    private TextField tfNama, tfNoTelp;
    private final Command cmdKeluar = new Command("Keluar", Command.EXIT, 1);
    private final Command cmdPilih = new Command("Pilih", Command.OK, 1);
    private final Command cmdSimpan = new Command("Simpan", Command.SCREEN, 1);
    private final Command cmdHapus = new Command("Hapus", Command.SCREEN, 1);
    private final Command cmdKembali = new Command("Kembali", Command.BACK, 1);

    public DemoRMS() {
        display = Display.getDisplay(this);

        alert = new Alert(null);
        alert.setTimeout(Alert.FOREVER);

        list = new List(null, ChoiceGroup.IMPLICIT);

        rs = null;

        //membuat atau membuka record sotre
        try {
            rs = RecordStore.openRecordStore("contohDB", true);
        } catch (RecordStoreException rse) {
            alert.setString("Record store tidak dapat dibuka. "
                    + "Aplikasi akan dihentikan");
            alert.setType(AlertType.ERROR);
            display.setCurrent(alert, null);
            System.exit(1);
        }
    }

    public void startApp() {
        form = new Form("Demo RMS");

        choicegorup = new ChoiceGroup("Menu : ", ChoiceGroup.EXCLUSIVE);
        choicegorup.append("Tambah Record", null);
        choicegorup.append("Daftar Record", null);

        form.append(choicegorup);
        form.addCommand(cmdKeluar);
        form.addCommand(cmdPilih);
        form.setCommandListener(this);
        display.setCurrent(form);

    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == cmdKeluar) {
            destroyApp(false);
            notifyDestroyed();
        } else if (c == cmdPilih) {
            switch (choicegorup.getSelectedIndex()) {
                case 0: {
                    entriData();
                    break;
                }
                case 1: {
                    lihatRecord();
                    break;
                }
            }
        } else if (c == cmdKembali) {
            display.setCurrent(form);
        } else if (c == cmdSimpan) {
            alert.setType(AlertType.INFO);
            if (!tfNama.equals("") && !tfNoTelp.equals("")) {
                tambahRecord(tfNama.getString(), tfNoTelp.getString());
                alert.setString("Data baru telah berhasil disimpan");
                display.setCurrent(alert, form);
            } else {
                alert.setString("Data NAMA dan NO. TELP "
                        + "tidak boleh kosong!");
                display.setCurrent(alert, entri);
            }
        } else if (c == cmdHapus) {
            int pos = list.getString(list.getSelectedIndex()).indexOf(" [");
            String nama = list.getString(list.getSelectedIndex()).substring(0, pos);
            hapusRecord(nama);
        }
    }

    public void tambahRecord(String nama, String noTelp) {
        byte[] temp = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeUTF(nama);
            dos.writeUTF(noTelp);
            temp = baos.toByteArray();
        } catch (IOException ioe) {
        }

        try {
            rs.addRecord(temp, 0, temp.length);
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }

    public void lihatRecord() {
        byte[] temp = null;
        list.setTitle("Daftar Record");
        list.deleteAll();
        try {
            re = rs.enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                int i = re.nextRecordId();
                temp = rs.getRecord(i);
                ByteArrayInputStream bais = new ByteArrayInputStream(temp);
                DataInputStream dis = new DataInputStream(bais);
                try {
                    String nama = dis.readUTF();
                    String noTelp = dis.readUTF();
                    list.append(nama + " [" + noTelp + "] ", null);
                } catch (IOException ioe) {
                }
            }
            list.addCommand(cmdKembali);
            list.addCommand(cmdHapus);
            list.setCommandListener(this);
            display.setCurrent(list);
        } catch (InvalidRecordIDException invID) {
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }

    public void hapusRecord(String nama) {
        byte[] temp = null;
        try {
            re = rs.enumerateRecords(null, null, false);
            
            while (re.hasNextElement()) {
                int i = re.nextRecordId();
                temp = rs.getRecord(i);
                ByteArrayInputStream bais = new ByteArrayInputStream(temp);
                DataInputStream dis = new DataInputStream(bais);
                try {
                    String vNama = dis.readUTF();
                    if (vNama.equals(nama)) {
                        rs.deleteRecord(i);
                        break;
                    }
                } catch (IOException ioe) {
                }
            }
            re.rebuild();
            lihatRecord();
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }

    public Form entriData(){
        entri = new Form("Entri Data");
        tfNama = new TextField("Nama : ", null, 25, TextField.ANY);
        tfNoTelp = new TextField("No. Telp : ", null, 15, TextField.PHONENUMBER);

        entri.append(tfNama);
        entri.append(tfNoTelp);
        entri.addCommand(cmdSimpan);
        entri.addCommand(cmdKembali);
        entri.setCommandListener(this);
        display.setCurrent(entri);
        return entri;
    }
}
